<?php
/*
 * @Descripttion: 
 * @Author: dedeye
 * @Date: 2020-02-28 23:04:02
 * @LastEditors: dedeye
 * @LastEditTime: 2020-02-29 16:52:23
 */

namespace app\http\middleware;

use app\admin\model\Rule;
use app\admin\model\Admin;

class AdminAuthCheck
{
    public function handle($request, \Closure $next)
    {
        $ruleinfo = $request->routeInfo()['rule'];
        $url = getUrlAndParam($ruleinfo);
        // dump();die;
        if(Session('admin_id') == config('admin.super_admin') 
            || in_array($url, config('admin.permission_url'))) {
            return $next($request);
        }
        $ruleInfo = Rule::field('id')->where(['url' => $url, 'status' => 1])->find();
        if(is_null($ruleInfo)) {
            return self::checkAjax();
        }
        if(!self::checkAuth($ruleInfo->id)) {
            return self::checkAjax();
        }
        return $next($request);
    }

    private static function checkAuth($ruleid)
    {
        $adminRule = Admin::field('id')
                    ->with('groups')
                    ->get(Session('admin_id'))
                    ->hidden(['groups.pivot'])->toArray();
        if(count($adminRule['groups']) == 0) {
            return false;
        }
        $rules = '';
        foreach($adminRule['groups'] as $k => $v) {
            $rules .= $v['rules'] . ',';
        }
        $rules = array_unique(explode(',', rtrim($rules, ',')));
        if(!in_array($ruleid, $rules)) {
            return false;
        }
        return true;
    }

    private static function checkAjax()
    {
        if(request()->isAjax()) {
            return resultJson(-1, '无访问权限');
        } else {
            return redirect('admin/index/noauth');
        }
    }
}
